import React, { Component } from 'react';
import ReactDom from 'react-dom';
import util from "@/common/util";
import ReactSwiper from 'reactjs-swiper';
import jquery from 'jquery';


class Creditcard extends Component {
    constructor(props) {
        super(props);
        this.state = {
            superlist: [],
            banklist: [],
            banklist2: [],
            hotlist: [],
            requirement: []
        }
    }

    async sendcode() {
        var wechatcode = util.getQuery().code;
        let res = await util.rjax({
            url: '/wxAuthenticate/getOpenId?code=' + wechatcode,
            type: 'post',
        }).catch((e) => {
            alert("e:" + e)
        })

        if (res) {
            console.log("if(res):" + res)
            sessionStorage.setItem("openid", res.data.openId)
        }
    }

    componentDidMount() {
        if (util.getQuery().code) {
            var openid = sessionStorage.getItem("openid")
            if (!openid || openid === 'null') {
                this.sendcode()
            }
        }
        else {
            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxeaccffdd3826280c&redirect_uri=http%3a%2f%2fwww.rongsue.com%2fwechat%2fcreditcard.html&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect`
        }

        //swiper滑动 
        var swiper = new Swiper('.swiper-container', {
            pagination: '.swiper-pagination',
            paginationClickable: true
        });

        let getconfig = async function () {
            let res = await util.rjax({
                url: "/wx/getwx?url=" + encodeURIComponent(window.location.href.split('#')[0]),
                type: "POST"
            })

            if (res) {
                wx.config({
                    debug: false,
                    appId: 'wxeaccffdd3826280c', // 必填，公众号的唯一标识
                    timestamp: parseInt(res.data.timestamp),// 必填，生成签名的时间戳
                    nonceStr: res.data.nonceStr,// 必填，生成签名的随机串
                    signature: res.data.signature,// 必填，签名
                    jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone']// 必填，需要使用的JS接口列表
                })
            }
        }
        getconfig()


        wx.ready(function () {
            //朋友圈
            wx.onMenuShareTimeline({// 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口（即将废弃）
                title: '各大银行信用卡免费办理', // 分享标题
                link: 'http://www.rongsue.com/wechat/creditcard.html', // 分享链接
                imgUrl: 'http://img0.rongsue.com/FtcG05DG5SyLU9y2jg_bSmqwHzvA',
                success: function (res) { },
                cancel: function (res) { },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });

            //朋友
            wx.onMenuShareAppMessage({//获取“分享给朋友”按钮点击状态及自定义分享内容接口（即将废弃）
                title: '各大银行信用卡免费办理', // 分享标题
                desc: '各大银行信用卡免费办理', // 分享描述
                link: 'http://www.rongsue.com/wechat/creditcard.html', // 分享链接
                imgUrl: 'http://img0.rongsue.com/FtcG05DG5SyLU9y2jg_bSmqwHzvA', // 分享图标
                type: '', // 分享类型,music、video或link，不填默认为link
                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                success: function () {
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        });
        this.superlist()
        this.banklist()
        this.hotlist()
    }

    // superlist
    async superlist() {
        let res = await util.rjax({
            url: '/card/list?recommend=1',
            type: 'get',
        })
        if (res.data.rows.length > 5) {
            this.setState({ superlist: res.data.rows.slice(0, 5) });
        } else {
            this.setState({ superlist: res.data.rows });
        }
    }

    // banklist
    async  banklist() {
        let res = await util.rjax({
            url: '/bank/list',
            type: 'get',
        })
        if (res.data.length > 8) {
            this.setState({ banklist: res.data.slice(0, 8) });
            jquery('.banks .secondslice').show()
            this.setState({ banklist2: res.data.slice(8) });
        } else {
            this.setState({ banklist: res.data });
        }
    }

    // hotlist
    async  hotlist() {
        let res = await util.rjax({
            url: '/card/list?hot=1',
            type: 'get',
        })
        if (res.data.rows.length >= 1) {
            this.setState({ hotlist: res.data.rows.slice(0, 1) });
            for (let i in res.data.rows) {
                this.setState({
                    requirement: res.data.rows[i].characters.split(/\n/g)
                })
            }
        }
    }

    render() {
        let superlist = this.state.superlist.map((item, index) => {
            return (
                <li data-id={item.id} key={index}>
                    <a href={item.link}>
                        <p className="tit">{item.name}</p>
                        <p className="intr">{item.summary}</p>
                        <img className="cardimg" src={item.image} alt="" />
                    </a>
                </li>
            )
        })

        let banklist = this.state.banklist.map((item, index) => {
            return (
                <li data-id={item.id} key={index}>
                    <a href={"./creditlist.html?dicId=" + item.id}>
                        <img className="img" src={item.logo} alt="" />
                        <p>{item.name}</p>
                    </a>
                </li>
            )
        })

        let banklist2 = this.state.banklist2.map((item, index) => {
            return (
                <li data-id={item.id} key={index}>
                    <a href={"./creditlist.html?dicId=" + item.id}>
                        <img className="img" src={item.logo} alt="" />
                        <p>{item.name}</p>
                    </a>
                </li>
            )
        })

        let hotlist = this.state.hotlist.map((item, index) => {
            return (
                <li className="hotcard" data-id={item.id} key={index}>
                    <a href={item.link}>
                        <p className="tit">{item.name}</p>
                        <p className="intr">{item.summary}</p>
                        <img className="cardimg" src={item.image} alt="" />
                        <div className="point">
                            <ul>
                                {this.state.requirement.map((item, index) =>
                                    <li key={index}>{item}</li>
                                )}
                            </ul>
                        </div>
                        <button className="applybtn">立刻申请</button>
                    </a>
                </li>
            )
        })

        return (
            <div>
                <div id="creditcard">
                    {/* super */}
                    <div className="super">
                        <h4><img src="/assets/wechat/rectangle.png" alt="" />达人推荐</h4>
                        <div className="supercard">
                            <ul>
                                {superlist}
                            </ul>
                        </div>
                    </div>
                    {/* banks */}
                    <div className="banks">
                        <h4><img src="/assets/wechat/rectangle.png" alt="" />热门银行</h4>
                        <div className="center">
                            <div className="swiper-container">
                                <div className="swiper-wrapper">
                                    <div className="swiper-slide">
                                        <ul>
                                            {banklist}
                                        </ul>
                                    </div>
                                    <div className="swiper-slide secondslice" style={{ display: 'none' }}>
                                        <ul>
                                            {banklist2}
                                        </ul>
                                    </div>
                                </div>
                                <div className="swiper-pagination" style={{ bottom: '-5px' }}></div>
                            </div >
                        </div >
                    </div>
                    {/* theme */}
                    <div className="theme">
                        <h4><img src="/assets/wechat/rectangle.png" alt="" />主题精选</h4>
                        <div className="themebox">
                            <div className="item">
                                <a href="./creditlist.html?greenHand=1">
                                    <img src="/assets/wechat/newcomer.png" alt="" />
                                    <span className="loanname">新手首选</span>
                                </a>
                            </div>
                            <div className="item">
                                <a href="./creditlist.html?travel=1">
                                    <img src="/assets/wechat/multiplepoint.png" alt="" />
                                    <span className="loanname">美食专享</span>
                                </a>
                            </div>
                            <div className="item">
                                <a href="./creditlist.html?point=1">
                                    <img src="/assets/wechat/bisout.png" alt="" />
                                    <span className="newloanname">多倍积分</span>
                                </a>
                            </div>
                        </div>
                    </div>
                    {/* hots */}
                    <div className="hots">
                        <h4 style={{ position: 'relative' }}>
                            <img src="/assets/wechat/rectangle.png" alt="" />热卡推荐
                             <a className="allcards" href="./creditlist.html?hot=1">
                                <span>全部卡片</span>
                                <img className="arrow" src="/assets/wechat/rightarrow.png" alt="" />
                            </a>
                        </h4>

                        <div className="hotsbox">
                            <ul>
                                {hotlist}
                            </ul>
                        </div>

                    </div>

                </div>
            </div >
        )
    }
}
ReactDom.render(<Creditcard />, document.getElementById("app"));